<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :visible.sync="dialog" :title="isAdd ? '新增用户' : '修改用户'" width="500px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="160px">
      <el-form-item label="账号" prop="busMainData.userAccount">
        <el-input v-model="form.busMainData.userAccount" :readonly="isAdd ? false : true" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="姓名" prop="busMainData.userName">
        <el-input v-model="form.busMainData.userName" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="电话" prop="busMainData.phone">
        <el-input v-model="form.busMainData.phone" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="邮件" prop="busMainData.email">
        <el-input v-model="form.busMainData.email" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="所属公司">
        <el-select v-model="cpyCodes" style="width: 300px;" multiple placeholder="请选择">
          <el-option
            v-for="(item, index) in cpyList"
            :key="item.cpyName + index"
            :label="item.cpyName"
            :value="item.cpyCode"/>
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态" prop="busMainData.userStatus">
        <el-select v-model="form.busMainData.userStatus" :style="style" placeholder="请选状态">
          <el-option
            v-for="(item) in dicts.user_status"
            :key="item.id"
            :label="item.dictName"
            :value="item.dictCode"/>
        </el-select>
      </el-form-item>
    </el-form>
    <div v-permission="['SYS_ADMIN']" slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addOrEdit, viewMainData, toAdd, toCopy } from '@/api/user'
import { getAllCpy } from '@/api/system/cpy'
import { isvalidPhone } from '@/utils/validate'

import md5 from 'js-md5'
export default {
  components: { },
  props: {
    sup_this: {
      type: Object,
      default: null
    }
  },
  dictTypes: ['user_status'],
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      isAdd: false,
      loading: false,
      dialog: false,
      style: 'width: 184px',
      cpyList: [],
      cpyCodes: [],
      form: {
        busMainData: {
          id: '',
          userName: '',
          userAccount: '',
          password: '',
          phone: '',
          email: '',
          avatar: '',
          cpyCode: '',
          orgCode: '',
          thirdAccount: '',
          userStatus: 'UNLOCK',
          enableFlag: 'Y',
          cpyVOS: []
        },
        busPageInfo: {
        }
      },
      rules: {
        'busMainData.userName': [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        'busMainData.userAccount': [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 4, max: 50, message: '长度在 4 到 10 个字符', trigger: 'blur' }
        ],
        'busMainData.phone': [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        'busMainData.email': [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    getAllCpy() {
      getAllCpy().then(res => {
        this.cpyList = res.data
      })
    },
    initDataOfBefore() {
      this.getAllCpy()
    },
    addData() {
      this.isAdd = true
      const data = { paramBean: { }}
      toAdd(data).then(res => {
        this.dialog = true
        this.form = res.data
      }).catch(err => {
        this.dialog = false
        console.log(err)
      })
    },
    copyData(mainId) {
      this.isAdd = true
      const data = { paramBean: { id: mainId }}
      toCopy(data).then(res => {
        this.dialog = true
        this.form = res.data
      }).catch(err => {
        this.dialog = false
        console.log(err)
      })
    },
    viewMainData(id) {
      this.isAdd = false
      const data = { paramBean: { id: id }}
      viewMainData(data).then(res => {
        this.form = res.data
      })
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          const _this = this
          _this.form.busMainData.cpyVOS = []
          this.cpyCodes.forEach(function(data, index) {
            const cpy = { cpyCode: data }
            _this.form.busMainData.cpyVOS.push(cpy)
          })

          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        }
      })
    },
    doAdd() {
      const userAccount = this.form.busMainData.userAccount.toLowerCase()
      const password = md5('123456' + userAccount)
      this.form.busMainData.userAccount = userAccount
      this.form.busMainData.password = password
      addOrEdit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          message: '默认密码：123456',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      addOrEdit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
    }
  }
}
</script>
